#include "unixhead.h"

#include <workflow/WFFacilities.h>
#include <workflow/WFHttpServer.h>
#include <workflow/HttpUtil.h>
#include <workflow/HttpMessage.h>

#include <iostream>
using namespace std;

static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int signum)
{
    cout << "wait group done\n";
    (void)signum;
    waitGroup.done();
}

void process(WFHttpTask * serverTask)
{
    cout << "process function is running\n";
    //解析请求
    auto req = serverTask->get_req();
    auto resp = serverTask->get_resp();

    printf("%s %s %s\n", req->get_method(), 
           req->get_request_uri(),
           req->get_http_version());

    protocol::HttpHeaderCursor cursor(req);
    std::string key, value;
    while(cursor.next(key, value)) {
        cout << key << ":" << value << endl;
    }
    cout << endl;
    //生成响应, 构造一个HttpResponse
    //起始行
    resp->set_http_version("HTTP/1.1");
    resp->set_status_code("200");
    resp->set_reason_phrase("OK");

    //首部字段
    resp->set_header_pair("Content-Type", "text/html");
    //消息体
    resp->append_output_body("<html><body>Welcome to workflow server</body></html>");


    //获取客户端的网络地址
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    socklen_t length = sizeof(addr);
    serverTask->get_peer_addr((struct sockaddr*)&addr, &length);
    if(addr.sin_family == AF_INET) {
        printf("ip:%s\n", inet_ntoa(addr.sin_addr));
        printf("port:%d\n", ntohs(addr.sin_port));
    }
}

int main()
{
    signal(SIGINT, sighandler);

    WFHttpServer server(process);

    //start的返回值监听成功返回值为0
    if(0 == server.start(8888)) {
        waitGroup.wait();
        server.stop();   
    } else {
        cout << "server start error!\n";
    }

    return 0;
}
